package com.config.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT 登录授权过滤器
 */
//@Component
public class JwtAuthTokenFilter extends OncePerRequestFilter {

    //token存放请求头的位置
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    //Bearer
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String authorization = httpServletRequest.getHeader(tokenHeader);
        System.out.println("authorization:" + authorization);
        //存在token
        if (null != authorization && authorization.startsWith(tokenHead)) {
            //截取token
            String token = authorization.substring(tokenHead.length());
            String username = jwtTokenUtil.getUserNameFormToken(token);
            //token存在用户, 但是未登录
            if (null != username && null == SecurityContextHolder.getContext().getAuthentication()) {
                /**
                 * userDetailsService 这个接口只有一个方法，我们通过在@link{com.config.SecurityConfig}
                 * 中重写的userDetailsService的方法 去走userService中的通过用户名获取用户信息的方法
                 */
                //下面进行登录 这个UserDetails实际上存储的是自己重写的loadUserByUsername中获取到User对象
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                //验证token是否有效，重新在Security全局中设置用户对象
                if (jwtTokenUtil.validateToken(token, userDetails)) {
                    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                }
            }
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
